﻿using AppsModel.Models;
using MVC_basic.Data_Layer;
using MVC_basic.Data_Layer.Interface;
using MVC_basic.Helpers;
using MVC_basic.Models;
using MVC_basic.ViewModels;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;

namespace MVC_basic.Controllers
{
    [Authorize]
    public class EditAppController : Controller
    {
        private readonly IdbApp db;
        public EditAppController(IdbApp DIdb)
        {
            db = DIdb;
            WebSecurity_Singleton.init();
        }

        public ActionResult Index()
        {
            int userId = WebSecurity.GetUserId(User.Identity.Name);
            List<App> apps = db.getAppsByUser(userId);
            return View(apps);
        }

        public ActionResult Edit(int id)
        {
            App app = db.getApp(id);
            if (app.appType == "Canvas")
                ViewBag.vm = CanvasAppViewModel.convert((CanvasApp)app);
            else if(app.appType == "Caja")
                ViewBag.vm = CajaAppViewModel.convert((CajaApp)app);
            return View(app);
        }

        [HttpPost]
        public ActionResult Canvas(CanvasApp canvasApp, string command)
        {
            if (command == "save")
            {
                db.updateCanvasApp(canvasApp.id, canvasApp.name, canvasApp.logoUrl, canvasApp.url, canvasApp.userId, canvasApp.canvasWidth, canvasApp.canvasHeight);
                ViewBag.vm = CanvasAppViewModel.convert(canvasApp);
            }
            else if (command == "delete")
            {
                db.deleteApp(canvasApp.id);
                return RedirectToAction("Index");
            }

            return View("Edit",canvasApp);
        }

        [HttpPost]
        public ActionResult Caja(CajaApp app, string command, HttpPostedFileBase zipfile)
        {
            if (command == "save")
            {
                db.updateCajaApp(app.id, app.name, app.logoUrl, app.acceptedUrl);
                ViewBag.vm = CajaAppViewModel.convert(app);
                REST_Helper.send(app.id, zipfile);
            }
            else if (command == "delete")
            {
                db.deleteApp(app.id);
                return RedirectToAction("Index");
            }

            return View("Edit", app);
        }
    }
}
